import { getToken, removeToken, setToken } from '@/utils/auth'
import { loginAPI, getUserInfoAPI, getUserDetailInfoAPI } from '@/api/user.js'

const state = {
  token: getToken() || '', // 默认token值
  userInfo: {} // 默认用户信息
}

const mutations = {

  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setToken(state.token)
  },

  // 删除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },

  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },

  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 优化异步,参数context.commit调用mutations,存到vuex中
  async userLogin(context, data) {
    const res = await loginAPI(data)
    context.commit('setToken', res.data)
  },

  // 获取用户信息
  async getUserInfo(context) {
    // 调接口,拿数据
    const res = await getUserInfoAPI()

    // 获取详情数据
    const detailInfo = await getUserDetailInfoAPI(res.data.userId)

    // 合并数据,并存入Vuex中
    context.commit('setUserInfo', { ...res.data, ...detailInfo.data })

    // 返回用户路由信息
    return res.data.roles.menus
  },

  // 用户退出登录
  async userLogout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

